package com.bridgetek.carlauncher;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

import java.util.ArrayList;

import com.bridgetek.carlauncher.adapter.MainPagerAdapter;
import com.bridgetek.carlauncher.fragment.FirstFragment;
import com.bridgetek.carlauncher.fragment.SecondFragment;

public class MainActivity extends FragmentActivity implements ViewPager.OnPageChangeListener {

    private ViewPager mViewPager;
    private HomeKeyEventBroadCastReceiver homeKeyReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendLauncherBroadcast();

        ArrayList<Fragment> list = new ArrayList<Fragment>();
        FirstFragment mFirstFragment = FirstFragment.newInstance();
        SecondFragment mSecondFragment = SecondFragment.newInstance();

        list.add(mFirstFragment);
        list.add(mSecondFragment);

        MainPagerAdapter mMainAdapter = new MainPagerAdapter(getSupportFragmentManager(), list);

        mViewPager = (ViewPager) findViewById(R.id.vv_mainViewpager);

        mViewPager.setAdapter(mMainAdapter);

        mViewPager.setOnPageChangeListener(this);

        homeKeyReceiver = new HomeKeyEventBroadCastReceiver();

        registerReceiver(homeKeyReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }

    /**
     * 开启开机录像
     */
    private void sendLauncherBroadcast() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.CAR_LAUNCHER_STARTED");
        sendBroadcast(intent);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (1 == position) {  //设置时间显示的位置
            Intent intent = new Intent();
            intent.setAction("android.intent.action_STATUS_BAR_CLOCK");
            intent.putExtra("state", 1);
            sendBroadcast(intent);
        } else {
            Intent intent = new Intent();
            intent.setAction("android.intent.action_STATUS_BAR_CLOCK");
            intent.putExtra("state", 0);
            sendBroadcast(intent);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(homeKeyReceiver);
    }

    private class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mViewPager.setCurrentItem(0);
        }
    }
}
